<?php
namespace Console\Config;

use Phalcon\Cli\Task;
use Phalcon\Di\FactoryDefault\Cli as DI;

class Base extends Task
{
    private $db = null;
    private $logger = null;
    private $di = null;

    public function initialize()
    {

    }

    public function getDI()
    {
        if ($this->di == null) {
            $this->di = (new DI())->getDefault();
        }
        return $this->di;
    }

    public function globalConfig()
    {
        return $this->getDI()->getShared('globalConfig');
    }

    /**
     * 获取数据库对象
     * @return \Phalcon\Db\Adapter\Pdo\Mysql
     */
    public function db()
    {
        if ($this->db == null) {
            $this->db = $this->getDI()->getShared('db');
        }
        return $this->db;
    }

    /**
     * 返回日志的操作方法
     * 使用方法
     * $this->logger()->debug('msg')
     * $this->logger()->error('msg')
     * $this->logger()->info('msg')
     * $this->logger()->warning('msg')
     * $this->logger()->notice('msg')
     *
     * @return \Phalcon\Logger\AdapterInterface
     */
    public function logger()
    {
        if ($this->logger == null) {
            $this->logger = $this->getDI()->getShared('logger');
        }
        return $this->logger;
    }

    /**
     * 记录错误日志
     *
     * @param string $type   数据库操作类型
     * @param string $query  数据库查询语句
     * @param string $reason 失败原因
     * @param string $file   发生的文件
     * @param int    $line   发生错误的行数
     *
     * @return void
     */
    public function errorLog($type, $query, $reason, $file, $line)
    {
        $this->Logger()->error(sprintf("数据库操作失败：类型[%s]，Query[%s]原因[%s][%s:%s]", $type, $query, $reason, $file, $line));
    }

}